/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cenluan.login;

import javax.servlet.http.HttpServletRequest;

import com.cenluan.common.Const;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

/**
 * 登录拦截器
 * 
 * @author peak
 * 
 */
public class LoginInterceptor implements Interceptor {

	public void intercept(ActionInvocation ai) {
		Controller controller = ai.getController();
		// 如果有清除登录拦截器的注解，跳过
		if (controller.getClass().getAnnotation(ClearLoginInterceptor.class) != null
				|| ai.getMethod().getAnnotation(ClearLoginInterceptor.class) != null) {
			ai.invoke();
			return;
		}
		HttpServletRequest request = controller.getRequest();

		if (controller.getSessionAttr(Const.SESSION_USER) != null) {
			ai.invoke();
			return;
		}
		/**
		 * 如果是post请求或者异步请求保存来源页面地址
		 */
		if (request.getHeader("x-requested-with") != null) {
			controller.setSessionAttr(Const.SESSION_REFERER,
					request.getHeader("Referer"));
			ai.getController().getResponse()
					.setHeader("login", request.getContextPath() + "/login");
			ai.getController().getResponse().setStatus(401);
			return;
		}

		if ("POST".equals(request.getMethod())) {
			controller.setAttr(Const.SESSION_REFERER,
					request.getHeader("Referer"));
		} else {// 非异步的get请求保存请求地址
			String queryString = StrKit.isBlank(request.getQueryString()) ? ""
					: "?" + request.getQueryString();
			controller.setSessionAttr(Const.SESSION_REFERER,
					request.getRequestURI() + queryString);
		}
		ai.getController().redirect("/login");

	}
}
